package com.sky.service.rider.Impl;

import cn.hutool.core.date.DateException;
import com.sky.constant.MessageConstant;
import com.sky.mapper.rider.CourierOrderMapper;
import com.sky.service.rider.CourierOrderService;
import com.sky.service.rider.CourierService;
import com.sky.vo.CourierTradeOrderDetailItemVO;
import com.sky.vo.CourierTradeOrderDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

import java.text.SimpleDateFormat;

@Service
@Slf4j
public class CourierOrderServiceImpl implements CourierOrderService {
    @Autowired
    CourierOrderMapper courierOrderMapper;
    @Override
    public CourierTradeOrderDetailVO findCourierMonthTradeOrderInfo(String courierId, String date) throws ParseException {
        if (null==courierId||null==date){
            throw new DateException(MessageConstant.DATA_ERROR);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String begin=date+"-01";
        //获取某月的天数
        int daysOfMonth = getDaysOfMonth(sdf.parse(begin));
        String end=date+"-"+daysOfMonth;
        log.info("begin===end:{},{}",begin,end);
      Double tradeOrderAverageDuration = courierOrderMapper.selectAve(courierId,begin,end);
      log.info("运单平均配送时长:{}",tradeOrderAverageDuration);
        Map<String,Object> map= courierOrderMapper.selectByStatus(courierId,begin,end);
        log.info("完成和取消的订单map,{}",map);
        Integer tradeOrdersCompleted = Integer.parseInt(map.get("4").toString());
        Integer  tradeOrdersCancelled=Integer.parseInt(map.get("5").toString());
        Integer  valiOder=courierOrderMapper.selectTimeRate(courierId,begin,end);
        log.info("有效订单数:{}",valiOder);
        Double tradOrderOnTimeRate= valiOder*1.0/tradeOrdersCompleted;
        log.info("运单配送准时率:{}",tradOrderOnTimeRate);
        //创建集合封装每天的日期
        List<LocalDate>datelist=new ArrayList<>();
        //转换String为LocalDate
        LocalDate beginTime = LocalDate.parse(begin);
        LocalDate endTime= LocalDate.parse(end);
        while (beginTime.isAfter(endTime)){
            datelist.add(beginTime);
           beginTime= beginTime.plusDays(1);
        }
        List<CourierTradeOrderDetailItemVO> tradeOrderDetails=courierOrderMapper.selectrDetailItem(courierId,datelist);
        return null;
    }




    //获取某月的天数
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

}
